package com.pingsky.apm.agent.core.trace;

import com.pingsky.apm.agent.core.AgentId;
import com.pingsky.apm.network.language.agent.v1.PSegment;
import com.pingsky.apm.network.language.agent.v1.PSpan;

import java.util.LinkedList;
import java.util.List;

public class TraceSegment {

    private String rpc;
    private String traceId;
    private String segmentId;
    private final long startTime;
    private final List<TraceSpan> spans;

    private final String agentId;
    private final String applicationName;

    private long endTime;
    private String parentSegmentId;

    public TraceSegment(String rpc) {
        this.rpc = rpc;
        this.traceId = TraceIdGenerator.generate();
        this.segmentId = GlobalIdGenerator.generate();
        this.startTime = System.currentTimeMillis();
        this.spans = new LinkedList<TraceSpan>();
        this.agentId = AgentId.INSTANCE.getAgentId();
        this.applicationName = AgentId.INSTANCE.getApplicationName();
    }

    public PSegment build() {
        return PSegment.newBuilder()
                .setRpc(rpc)
                .setTraceId(traceId)
                .setSegmentId(segmentId)
                .setParentSegmentId(parentSegmentId)
                .setStartTime(startTime)
                .setEndTime(endTime)
                .setAgentId(agentId)
                .setApplicationName(applicationName)
                .addAllSpan(buildPSpans())
                .build();
    }

    private List<PSpan> buildPSpans() {
        List<PSpan> list = new LinkedList<PSpan>();
        if (null != spans) {
            for (TraceSpan span : spans) {
                list.add(span.build());
            }
        }
        return list;
    }
}
